/**
 * WebSocket客户端 - 用于流式AI对话
 * 实现打字机效果和实时通信
 */
import { io, Socket } from 'socket.io-client'

export interface StreamMessage {
  type: 'start' | 'chunk' | 'end' | 'error'
  content?: string
  session_id?: string
  requirement_id?: string
  error?: string
}

export class WebSocketClient {
  private socket: Socket | null = null
  private isConnected = false
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectDelay = 1000
  
  constructor(private url: string = 'http://127.0.0.1:5001') {
    this.connect()
  }
  
  private connect() {
    try {
      this.socket = io(this.url, {
        transports: ['websocket', 'polling'],
        timeout: 20000,
        forceNew: true
      })
      
      this.setupEventListeners()
    } catch (error) {
      console.error('WebSocket连接失败:', error)
    }
  }
  
  private setupEventListeners() {
    if (!this.socket) return
    
    this.socket.on('connect', () => {
      console.log('WebSocket已连接到:', this.url)
      this.isConnected = true
      this.reconnectAttempts = 0
    })
    
    this.socket.on('disconnect', (reason) => {
      console.log('WebSocket断开连接:', reason)
      this.isConnected = false
      
      if (reason === 'io server disconnect') {
        // 服务器主动断开，需要重连
        this.handleReconnect()
      }
    })
    
    this.socket.on('connect_error', (error) => {
      console.error('WebSocket连接错误:', error)
      console.error('连接URL:', this.url)
      this.handleReconnect()
    })
    
    // 添加通用错误监听
    this.socket.on('error', (error) => {
      console.error('WebSocket通用错误:', error)
    })
  }
  
  private handleReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)
      
      setTimeout(() => {
        this.connect()
      }, this.reconnectDelay * this.reconnectAttempts)
    } else {
      console.error('WebSocket重连失败，已达到最大重试次数')
    }
  }
  
  // 开始流式生成
  public startStream(
    requirementId: string,
    sessionId: string,
    message?: string,
    onMessage?: (data: StreamMessage) => void,
    onError?: (error: string) => void
  ) {
    if (!this.socket || !this.isConnected) {
      console.error('WebSocket未连接，无法开始流式生成')
      onError?.('WebSocket未连接')
      return
    }
    
    console.log('开始流式生成:', { requirementId, sessionId, message })
    
    // 清理之前的监听器
    this.socket.off('stream_message')
    this.socket.off('stream_error')
    
    // 监听流式消息
    this.socket.on('stream_message', (data: StreamMessage) => {
      console.log('收到流式消息:', data)
      onMessage?.(data)
    })
    
    // 监听错误
    this.socket.on('stream_error', (error: { message?: string; error?: string }) => {
      console.log('WebSocket收到错误事件:', error)
      const errorMessage = error.error || error.message || '未知错误'
      console.error('流式生成错误:', errorMessage)
      onError?.(errorMessage)
    })
    
    // 发送生成请求
    this.socket.emit('start_generation', {
      requirement_id: requirementId,
      session_id: sessionId,
      message: message || ''
    })
  }
  
  // 停止流式生成
  public stopStream() {
    if (this.socket) {
      this.socket.emit('stop_generation')
      this.socket.off('stream_message')
      this.socket.off('stream_error')
    }
  }
  
  // 发送用户消息
  public sendMessage(sessionId: string, message: string) {
    if (!this.socket || !this.isConnected) {
      throw new Error('WebSocket未连接')
    }
    
    this.socket.emit('user_message', {
      session_id: sessionId,
      message
    })
  }
  
  // 加入会话房间
  public joinSession(sessionId: string) {
    if (this.socket && this.isConnected) {
      this.socket.emit('join_session', { session_id: sessionId })
    }
  }
  
  // 离开会话房间
  public leaveSession(sessionId: string) {
    if (this.socket && this.isConnected) {
      this.socket.emit('leave_session', { session_id: sessionId })
    }
  }
  
  // 获取连接状态
  public getConnectionStatus() {
    return {
      isConnected: this.isConnected,
      reconnectAttempts: this.reconnectAttempts
    }
  }
  
  // 断开连接
  public disconnect() {
    if (this.socket) {
      this.socket.disconnect()
      this.socket = null
      this.isConnected = false
    }
  }
}

// 创建全局WebSocket实例
export const wsClient = new WebSocketClient()

// 导出便捷方法
export const useWebSocket = () => {
  return {
    client: wsClient,
    isConnected: () => wsClient.getConnectionStatus().isConnected,
    startStream: wsClient.startStream.bind(wsClient),
    stopStream: wsClient.stopStream.bind(wsClient),
    sendMessage: wsClient.sendMessage.bind(wsClient),
    joinSession: wsClient.joinSession.bind(wsClient),
    leaveSession: wsClient.leaveSession.bind(wsClient)
  }
}